package com.maysahar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.maysahar.model.Entry;

public class EntryDAO {
	  private SQLiteDatabase database;
	  private DatabaseHelper dbHelper;
	  private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
	  
	  public EntryDAO(Context context) {
	    dbHelper = new DatabaseHelper(context);
	  }

	  public void open() throws SQLException {
	    database = dbHelper.getWritableDatabase();
	  }

	  public void close() {
	    dbHelper.close();
	  }

	  public long create(Entry entry) {
		  
		    ContentValues values = new ContentValues();
		    values.put(DatabaseHelper.COLUMN_NAME, entry.getName());
		    values.put(DatabaseHelper.COLUMN_VALUE , entry.getValue());
		    values.put(DatabaseHelper.COLUMN_SETTING, entry.getSetting());
		    values.put(DatabaseHelper.COLUMN_VERSION, entry.getVersion());
		    values.put(DatabaseHelper.COLUMN_MODIFIED_ON, dateFormat.format(new Date()));
		    
		    long insertId = database.insert(DatabaseHelper.TABLE_ENTRIES, null,
		        values);
		    return insertId;

	  }

	  public void deleteAll() {
	    database.delete(DatabaseHelper.TABLE_ENTRIES, null, null);
	    database.execSQL("delete from sqlite_sequence where name='" + DatabaseHelper.TABLE_ENTRIES + "'");
	  }

	public ArrayList<Entry> select(String whereClause) throws Exception {
		String orderByClause = null;
		Cursor cursor = database.query(DatabaseHelper.TABLE_ENTRIES, 
				new String[]{DatabaseHelper.COLUMN_ID,
				DatabaseHelper.COLUMN_NAME,
				DatabaseHelper.COLUMN_VALUE,
				DatabaseHelper.COLUMN_SETTING,
				DatabaseHelper.COLUMN_VERSION,
				DatabaseHelper.COLUMN_MODIFIED_ON}, whereClause, null, null, null, orderByClause);
	    cursor.moveToFirst();
	    ArrayList<Entry> entries = new ArrayList<Entry>();
	    while (!cursor.isAfterLast()) {
	    	int c = 0;
	    	int index = cursor.getInt(c++);
	    	String name = cursor.getString(c++);
	    	String value = cursor.getString(c++);
	    	int setting = cursor.getInt(c++);
	    	int version = cursor.getInt(c++);
	    	String dateTimeStr = cursor.getString(c++);
	    	Date date = dateFormat.parse(dateTimeStr);

	    	Entry entry = new Entry();
	    	entry.setId(index);
	    	entry.setName(name);
	    	entry.setValue(value);
	    	entry.setSetting(setting);
	    	entry.setValue(value);
	    	entry.setModifiedOn(date);
	    	entry.setVersion(version);
	    	entries.add(entry);
	        cursor.moveToNext();
	    }
	    // Make sure to close the cursor
	    cursor.close();
	    return entries;
	}

	  

}
